<!--
    字幕与配音
-->
<script setup>
import {
  ref,
  reactive,
  toRefs,
  watch,
  onMounted,
  onUnmounted,
  nextTick,
  computed,
  provide,
  h,
  createVNode,
} from "vue";
import dayjs from "dayjs";
import utils from "@/common/utils/utils.js";

// 生成随机id
import { nanoid } from "nanoid";

// 富文本
import Global_TextEditing from "./Component/Global_TextEditing.vue";

// 批量处理富文本导入
import {
  importListToRichtext,   // 视频截取首帧画面
  captureFirstFrame,
} from "@/common/utils/richTextProcessing.js";

// 文案库组件
import CopyLibraryModal from "@/components/AddTextModal/CopyLibraryModal.vue";
const copyLibraryModal = ref(null);

// 文案仿写
import TextImitationDialog from "@/views/shotstack/components/TextImitationDialog/index.vue";
const TextImitationDialogRef = ref(null);

// icon
import {
  CloseOutlined,
  DeleteOutlined,
  PlusOutlined,
  UploadOutlined,
  LoadingOutlined,
  PauseOutlined,
  CaretRightOutlined,
  ExclamationCircleOutlined,
  FileDoneOutlined,
} from "@ant-design/icons-vue";
import {
  getTextWidthUsingCanvas,
  baseTts_config,
  sizeData,
  resetXY,
  xLocation,
  hexToRgba,
  subtitleHeightratio,
  estimateAudioDuration,
  processText,
} from "../../utools/index.js";
// 提示框
import { Modal } from "ant-design-vue";

// 全局轻提示
import { message } from "ant-design-vue";

//
import request from "@/common/utils/request";

// 选择文件组件
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

import AIWritingAssistant from "@/views/shotstack/MuseMixedCut/mixedCutCreat/components/AIWritingAssistant.vue";
// 仓库
import { useStore } from "vuex";
const store = useStore();

import { useRoute, useRouter } from "vue-router";
const route = useRoute();

// 字幕与配音组件
import SubtitlesFontStyleComponent from "./globalSubtitlesFontStyleComponent.vue";
// 手机组件
import { DraggableContainer } from "vue3-draggable-resizable";

import Vue3DraggableResizable from "vue3-draggable-resizable";
//default styles
import "vue3-draggable-resizable/dist/Vue3DraggableResizable.css";

import ViewAudioModel from "@/views/shotstack/MuseMixedCut/mixedCutCreat/components/Component/ViewAudioModel.vue";

// 仓库中的混剪数据
const VideoMashup = computed(() => {
  return store.state.shotstack.VideoMashup;
});

// 仓库中的字幕数据
const Global_tts_config = computed(() => {
  return store.state.shotstack.Global_tts_config;
});

// 获得字体大小转换的比例
const scaleData = computed(() => {
  const { showHeight, showWidth } = store.state.videoMixCut.VideoMashup;
  return resetXY(showHeight, showWidth);
});

// 当前编辑的富文本项的tts_id
const currentId = computed({
  get() {
    return store.state.shotstack?.global_edit_tts_id || "";
  },
  set(val) {
    store.commit("MODIFY_GLOBAL_TTS_ID", val);
  },
});

// 背景设置的参数
const bgc = computed(() => {
  const data = store.state.shotstack.VideoMashup.background
  // debugger
  if (data?.type == 1) {
    return {
      'background': data.rgba
    }
  } else if (data?.type == 2 || data?.type == 3) {
    let url = data.material_urls[0]
    return {
      'background': `url(${url})`,
      'background-position': 'center',
      'background-size': 'cover'
    }
  } else {
    return {
      'background': '#707070'
    }
  }
});

// 分开字幕与配音的数据
const dataSeparation = computed(() => {
  const obj = {
    tts_config_text: [],
    tts_config_audio: [],
  };
  if (Global_tts_config.value && Global_tts_config.value?.configs?.length) {
    Global_tts_config.value.configs.forEach((ele) => {
      if (ele.tab_id == "text") {
        obj.tts_config_text.push(ele);
      } else {
        obj.tts_config_audio.push(ele);
      }
    });
  }
  return obj;
});

/**
 * 当前富文本编辑项的数据
 * @param { text: 前编辑项(subtitle)的文本, id: 当前编辑项(subtitle)的id }
 */
const editSubtitleData = computed(() => {
  return store.state.shotstack.editSubtitleData;
});

// 当前正在编辑的 subtitle项
const targetSubtitle = computed(() => {
  let subtitle = null;
  let targettTS = Global_tts_config.value?.configs.find(
    (ele) => ele.tts_id == currentId.value
  );
  subtitle = targettTS?.subtitle.find(
    (item) => item.subtitle_id == editSubtitleData.value.id
  );

  return subtitle || targettTS?.subtitle?.[0];
});

const editSubtitleItem = computed({
  get() {
    return !!targetSubtitle.value
      ? {
        x: targetSubtitle.value.showX,
        y: targetSubtitle.value.y,
        text: targetSubtitle.value.text,
      }
      : {
        x: 0,
        y: 0,
        text: "",
      };
  },
});

const FlowerList = computed(() => store.state.shotstack.FlowerList);

// 模板广场页面带过来的 id
const queryData = computed(() => {
  return {
    viewType: route.query?.viewType, // 1模板详情, 2混剪详情
    id: route.query?.id, // 详情id
    key: route.query?.key, // 获取详情的id键名
    type: route.query?.type, // 用于区分新建的类型
    templateType: route.query?.templateType, // 用于区分查看模板详情的类型 1为我的模板 2为模板广场
    createType: route.query?.createType, // 用于区分模板创建类型 1为网络连接 2为素材库 3为手动创建
    useType: route.query?.useType, // 用于区分模板使用的类型 edit 编辑 view 详情 use使用
    typeofuse: route.query?.typeofuse, // 用于区分模板点击使用使用的类型 myTemplate为我的模板 squareTemplate为模板广场
    openType: route.query?.openType, // 用于区分模板点击使用使用的类型 myTemplate为我的模板 squareTemplate为模板广场
  };
});

// 控制手机显示隐藏
const phoneVisible = ref(false);
// 加载效果
const loading = ref(false);

// 手机
const props = defineProps({
  title: {
    type: String,
    default: "全局配置 - 全局字幕配音",
  },
});

// 字体组件
const Subtitles_FontStyleComponent = ref(null);

// 修改当前的展开项
const foldManual = (id) => {
  currentId.value = id;
  store.commit("SET_GLOBALTTS_CURRENT_ID", id);
};

// 添加字幕项
const addeditorArr = () => {
  // 只有text 有
  const pushItem = JSON.parse(
    JSON.stringify(dataSeparation.value.tts_config_text[0])
  );
  const id = nanoid();
  pushItem.tts_id = id;
  pushItem.tab_id = "text";
  const pushSubtitle = JSON.parse(
    JSON.stringify(dataSeparation.value.tts_config_text[0]?.subtitle[0])
  );
  pushSubtitle.subtitle_id = nanoid();
  pushSubtitle.text = "";
  pushSubtitle.ssml = "<speak></speak>";
  pushSubtitle.start_time = 0;
  pushSubtitle.end_time = 0;
  pushSubtitle.audio_url = "";
  pushSubtitle.duration = 0;

  pushItem.subtitle = [pushSubtitle];
  pushItem.ssmlContent = `<speak subid="${pushSubtitle.subtitle_id}" tts_id="${id}"></speak>`;
  Global_tts_config.value.configs.push(pushItem);

  store.commit("INIT_GLOBALTTSCONFIG_DATA", Global_tts_config.value);
  nextTick(() => {
    // 修改展开的项
    currentId.value = pushItem.tts_id;
    store.commit("SET_GLOBALTTS_CURRENT_ID", pushItem.tts_id);
  });
};

// 切换字幕生成方式
const switchDisplay = (type) => {
  Global_tts_config.value.configs_type = type;
  store.commit("INIT_GLOBALTTSCONFIG_DATA", Global_tts_config.value);
  if (type == "text") {
    currentId.value = dataSeparation.value.tts_config_text[0].tts_id;
  } else {
    currentId.value = dataSeparation.value.tts_config_audio[0].tts_id;
  }
};

// 拖动结束修改 x和y的位置
const dragEndHandle = (data) => {
  nextTick(() => {
    const dom = document.getElementById("editor_content_p");
    const width = dom.offsetWidth;
    store.commit("MODIFY_GLOBAL_SUBTITLES_POSITION", {
      x: data.x - width / 2,
      showX: data.x,
      y: data.y,
      configs_type: Global_tts_config.value.configs_type,
      id: targetSubtitle.value?.subtitle_id,
    });
  });
};

// 获取当前选中的弹幕
const resizableStyle = computed(() => {
  let returnVal =
    background.value.type == "color"
      ? {
        background: background.value.url,
      }
      : {
        background: `url(${background.value.url})`,
        "background-size": "100%" /* 或者其他合适的设置 */,
        "background-repeat": "no-repeat",
        "background-position": "center",
      };
  return {
    // background: "#707070",
    // background: "#e6e6e6",
    width: sizeData.value.draggableWidth + "px",
    height: sizeData.value.draggableHeight + "px",
    transition: "all .3s",

    ...returnVal
  };
});
const showImg = ref(true);

// 文字外边框的宽高
const ResizableWidth = ref("100%");
const Resizableheight = ref("100%");
// 字体列表
const typefaceOptions = ref([]);
// 当前使用的字体样式
// 计算字体样式
const coverStyle = computed(() => {
  return function () {
    nextTick(() => {
      let isDom = document.getElementById("editor_content_p");
      ResizableWidth.value = isDom?.offsetWidth + 2;
      Resizableheight.value = isDom?.offsetHeight;
    });
    // });
    if (targetSubtitle.value) {
      // 计算字体的显示比例
      const size = targetSubtitle.value.font_size;
      const width = VideoMashup.value.showWidth;
      const height = VideoMashup.value.showHeight;
      // 获取当前缩放的比例
      const { scaleWidth } = resetXY(height, width);
      const font_size = size / scaleWidth;

      let flower_style;
      // 获取花字的对应样式
      const shadow = () => {
        let { borderw, bordercolor } =
          targetSubtitle.value.preset_styles_config;
        borderw = borderw / 3;
        if (borderw && bordercolor) {
          const shadows = [];
          for (let x = -borderw; x <= borderw; x++) {
            for (let y = -borderw; y <= borderw; y++) {
              if (x !== 0 || y !== 0) {
                shadows.push(`${x}px ${y}px 0 ${bordercolor}`);
              }
            }
          }
          return shadows.join(",");
        } else {
          return "";
        }
      };
      // 获取花字的对应样式
      flower_style = {
        // 字体颜色
        color:
          targetSubtitle.value?.preset_styles_config.fontcolor ||
          targetSubtitle.value.color,
        // 转换背景色和透明度
        "background-color": hexToRgba(
          targetSubtitle.value?.preset_styles_config.boxcolor,
          targetSubtitle.value?.preset_styles_config.box_color_alpha
        ),
        // 整体透明度
        // 边框的粗细
        padding: `${targetSubtitle.value?.preset_styles_config?.boxborderw
          ? targetSubtitle.value?.preset_styles_config?.boxborderw / 4
          : 0
          }px`,
        // "border-radius":
        // targetSubtitle.value?.preset_styles_config.boxradius / 3 + "px",

        "text-shadow": shadow(),
      };

      const reTurnData = {
        cursor: "grab",
        "font-family": targetSubtitle.value.font_family,
        "font-size": font_size + "px",
        color: targetSubtitle.value.color,
        "background-color": targetSubtitle.value.bg_color,
        textAlign:
          targetSubtitle.value.alignment == "left"
            ? "left"
            : targetSubtitle.value.alignment == "right"
              ? "right"
              : "center",
        fontWeight: targetSubtitle.value.bold == 1 ? "bold" : "normal",
        fontStyle: targetSubtitle.value.italic == 1 ? "italic" : "normal",
      };

      if (!!flower_style) {
        return {
          ...reTurnData,
          ...flower_style,
        };
      } else {
        return reTurnData;
      }
      /* 右下 */
      // textAlign: "center",
      // 'overflow': 'hidden',
      // 'width': '100%',
      // 'height': coverList.value.height + 'px',
      // 'opacity': tergetItem.opacity
      // 'display': 'flex',
      // 'align-items': tergetItem.verticle_position == 'top' ? 'start' : tergetItem
      //   .verticle_position == 'center' ? 'center' : 'end',
      // 'justify-content': tergetItem.alignment == 'left' ? 'start' : tergetItem.align_type ==
      //   'center' ? 'center' : 'end',
    } else {
      return {};
    }
  };
});

// 控制抽屉显示
const visible = ref(false);

watch(
  () => visible.value,
  (nv) => {
    // 清空当前试听的状态
    store.commit("SETVIDEOPLAYING_DATA", {
      isPlay: false,
      audio_url: "",
      reset: false, // 是否从头播放
      changeUrl: false, // 是否修改url
    });
    if (!nv) {
      start_upload_Alldata.value = [];
    }
  }
);

// 宽度侦听器
const resizeObserver = ref(null);
// span 的宽度
const spanWidth = ref("");
// 打开抽屉的 - 获取正在操作项的项
const openDrawer = () => {
  // 侦听手机组件 span的宽度, 动态设置该项数据的x和y
  resizeObserver.value = new ResizeObserver((entries) => {
    for (let entry of entries) {
      let subtitle;
      nextTick(() => {
        let targettTS = Global_tts_config.value.configs.find(
          (ele) => ele.tts_id == currentId.value
        );
        subtitle = targettTS?.subtitle.find(
          (item) => item.subtitle_id == editSubtitleData.value.id
        );
        spanWidth.value = entry.contentRect.width;

        !!subtitle &&
          visible.value != false &&
          (() => {
            store.commit("MODIFY_GLOBAL_SUBTITLES_POSITION", {
              x: subtitle.showX - spanWidth.value / 2,
              showX: subtitle.showX,
              y: subtitle.y,
              configs_type: Global_tts_config.value.configs_type,
              id: subtitle.subtitle_id,
            });
            console.log(subtitle, subtitle.subtitle_id, "修改的项");
          })();
      });
    }
  });

  useBgc()
  // currentDrawerIndex.value = index.index;
  // 克隆数据, 用于修改 最后保存
  store.commit(
    "INIT_GLOBALTTSCONFIG_DATA",
    JSON.parse(JSON.stringify(VideoMashup.value.global_tts_config))
  );
  visible.value = true;

  nextTick(() => {
    // 侦听 span 的宽度
    resizeObserver.value.observe(document.getElementById("editor_content_p"));

    if (Global_tts_config.value.configs_type == "text") {
      currentId.value = dataSeparation.value.tts_config_text[0].tts_id;
    } else {
      currentId.value = dataSeparation.value.tts_config_audio[0].tts_id;
    }
    store.commit("SET_GLOBALTTS_CURRENT_ID", currentId.value);
  });

  // 获取字体数据 + 手机状态数据回显
  // getFontClass();
  setTimeout(() => {
    phoneVisible.value = true;
  }, 550);
};

const background = ref({
  type: "color",
  url: "transparent",
});

// 使用的背景
const useBgc = async () => {
  // 判断使用的背景
  const find = VideoMashup.value.resource_data.find(
    (ele) => ele.material_list.length
  );

  if (!find) return (background.value = { url: "transparent", type: "color" });
  const material = find.material_list[0];

  if (material?.scene_type == "video") {
    const url = await captureFirstFrame(material.material_url);
    
    if (url) {
      background.value = { url, type: "img" };
    } else {
      background.value = "transparent";
      background.value = { url: "transparent", type: "color" };
    }
  } else if (material?.scene_type == "image") {
    const url = material.material_url;
    url
      ? (background.value = { url, type: "img" })
      : (background.value = { url: "transparent", type: "color" });
  } else {
    background.value = { url: "transparent", type: "color" };
  }
};

// 按钮的loding
const submitLoading = ref(false);

// 点击确定保存数据
const submitConfirm = async () => {
  // debugger
  const type = Global_tts_config.value.configs_type;
  // 判断最后是否关闭弹窗
  let isClose = ref(true);
  if (type == "text") {
    const textEmpty = dataSeparation.value.tts_config_text.every((ele) => {
      return ele.subtitle.every(
        (i) => !!i.text.trim() && i.text.trim() !== "\n"
      );
    });
    if (dataSeparation.value.tts_config_text.length > 1) {
      if (!textEmpty)
        return message.warning("字幕组中存在空项,请填写或删除后再保存");
    } else {
      if (dataSeparation.value.tts_config_text[0].subtitle.length > 1) {
        // 多项subtitle 有空项
        if (!textEmpty) {
          return message.warning("字幕组中存在空项,请填写或删除后再保存");
        }
      }
    }
    let isNotEmpty = false;
    // 文本需要检测是否开启音频
    // 是否有文本
    isNotEmpty = dataSeparation.value.tts_config_text.some((ele) => {
      return ele.subtitle.some(
        (i) => !!i.text.trim() && i.text.trim() !== "\n"
      );
    });

    // 是否开启音频
    let showVoice = dataSeparation.value.tts_config_text.some((ele) => {
      return ele.showVoice;
    });
    // debugger
    // 有文本并且开启了配音
    if (isNotEmpty && showVoice) {
      // 获取全局音频中的所有音频
      const textAndSubtitleId = dataSeparation.value.tts_config_text.flatMap(
        (ele) =>
          ele.subtitle
            .filter(
              (sub) =>
                !!sub.text.trim() && sub.text.trim() !== "\n" && !sub.audio_url
            )
            .map((sub) => ({ text: sub.ssml, id: sub.subtitle_id }))
      );
      // 有需要获取配音的字幕
      if (Array.isArray(textAndSubtitleId) && textAndSubtitleId.length >= 1) {
        // 按钮loding
        submitLoading.value = true;
        message.loading("字幕语音转换中...", 0);
        // 有需要获取音频的选项
        const { speed, tone_id, volume, emotion_category, emotion_intensity } =
          dataSeparation.value.tts_config_text[0];

        const requestData = {
          text: textAndSubtitleId,
          speed,
          timbre_id: tone_id,
          volume,
          emotion_category,
          emotion_intensity,
          unique: nanoid(),
        };
        console.log(requestData, "提交的数据requestData");

        // 找到对应的数据, 存放数据
        const setVoice = (arr) => {
          dataSeparation.value.tts_config_text.flatMap((sub, index) => {
            sub.subtitle.forEach((ele) => {
              const findTarget = arr.find((i) => i.id == ele.subtitle_id);
              if (!!findTarget) {
                ele.audio_url = findTarget.audio;
                ele.duration = findTarget.duration * 1000;
                if(findTarget?.duration_ms && findTarget?.duration_ms > 0){
                  ele.duration = findTarget.duration_ms;
                } 
                ele.end_time = ele.duration;
                ele.media_id = findTarget?.oss_media_id || "";
                ele.material_path = findTarget?.material_path || "";
              }
            });
          });
        };
        // 创建一个函数用于延迟请求
        const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

        try {
          // 视频组编辑 点确定的时候,  会发请求 只有当每一项内部没有音频或者失效的时候 会获取这一项的音频  然后存进去,
          const res = await request.post(
            "/work_ai",
            "/user/shotstack/textToVoice/many",
            { ...requestData, mexid_all: true }
          );

          // 使用新的获取音频接口
          const getItemVoice = async () => {
            const itemVoice = await request.get(
              "/work_ai",
              `/user/shotstack/textToVoice/many/result/${requestData.unique}`
            );
            console.log("单项的轮询结果123", itemVoice);
            if (itemVoice?.code && itemVoice?.code != 1000) {
              throw new Error(itemVoice);
            }
            if (itemVoice?.result?.status) {
              if (itemVoice.result.status == "loading") {
                await delay(2000);
                await getItemVoice();
                return;
              }
              if (itemVoice.result.status == "error") {
                return message.error("音频获取失败!");
              }
            } else {
              console.log("itemVoice?.result 有数据啦", itemVoice?.result);
              setVoice(itemVoice?.result);
            }
          };

          await getItemVoice();
        } catch (error) {
          message.destroy();
          submitLoading.value = false;
          isClose.value = false;
          nextTick(() => {
            message.error("字幕语音转换失败,请重试!");
          });
          // debugger
        }
        message.destroy();
        submitLoading.value = false;
      } else {
        // 都有音频 => 修改素材的时长为第一个字幕组的音频时长
        // let time = 0
        // let targetConfig = dataSeparation.value.tts_config_text.find(ele => ele.subtitle.some(i => !!i.text.trim() && i.text.trim() !== "\n"))
        // targetConfig.subtitle.forEach(ele => {
        //   time += ele.duration
        // })
        // console.log(targetConfig, 'targetConfig');
        // Global_tts_config.value.configs?.material_list.forEach(ele => {
        //   ele.end_time = time ? time : 1000
        // })
      }
    } else if (isNotEmpty && !showVoice) {
      // 有文本 ,但是没有开启音频配音, 将当前的预估时长, 赋值给总时长一项
      let text = "";
      let time = 0;
      dataSeparation.value.tts_config_text[0].subtitle.forEach((ele) => {
        const data = processText(ele.ssml);
        text += data.resultText;
        time += data.totalTime;
      });
      if (text) {
        // 用文本计算大约的时长
        const durationData = Math.ceil(+estimateAudioDuration(text));
        if (time) {
          // 如果有停顿的时间, 需要加上停顿时间
          // time = time / 1000
          dataSeparation.value.tts_config_text[0].duration =
            durationData * 1000 + time;
        } else {
          dataSeparation.value.tts_config_text[0].duration = durationData;
        }
      } else {
        dataSeparation.value.tts_config_text[0].duration = 0;
      }
    }
  }

  // 将全局设为开启状态
  Global_tts_config.value.type = 1;
  submitLoading.value = false;

  // 将所有视频组的时长设置 改为原始时长
  VideoMashup.value.resource_data.forEach((ele) => {
    ele.material_list.forEach((item) => {
      // 将图片设置为 3秒, 视频设置为原始时长
      if (ele.time_strategy != 0 && ele.time_strategy.type != 3) {
        ele.time_strategy.type = 0;
        if (item.scene_type == "image") {
          item.end_time = 3000;
        } else {
          item.end_time = +item.material_duration;
        }
      }
    });
  });

  // 父项 添加总时长
  dataSeparation.value.tts_config_text.forEach((ele) => {
    if (ele.subtitle.length) {
      const allTime = ele.subtitle.reduce(
        (all, item) => +all + +item.duration,
        0
      );
      ele.duration = +allTime;
    }
  });

  if (isClose.value) {
    store.dispatch("SetVideoMashupItem", {
      key: "global_tts_config",
      value: JSON.parse(JSON.stringify(Global_tts_config.value)),
    });
    closeDrawer();
  }
};

// 关闭抽屉的方法
const closeDrawer = () => {
  resizeObserver.value.unobserve(document.getElementById("editor_content_p"));
  visible.value = false;
  phoneVisible.value = false;
};

const close = () => {
  Modal.confirm({
    title: "温馨提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "当前未保存，是否退出设置，退出后将不会保存这次编辑",
    cancelText: "取消",
    okText: "确认",
    onOk() {
      closeDrawer();
    },
    onCancel() { },
    class: "test",
  });
};

// 打开AI写作助手弹窗
const aiWritingAssistant = ref(null);
const openAI = () => {
  // 打开抽屉 初始赋值
  aiWritingAssistant.value.showDrawer({
    data: JSON.parse(JSON.stringify(Global_tts_config.value)),
    type: "tts",
  });
};

const CloseAIDrawer = () => {
  openDrawer();
};
const showUploadState = ref(false);

// 成功上传
const start_upload = ref(null);
const start_upload_loading = ref(false);
const start_upload_name = ref("");
const start_upload_Alldata = ref([]);

const handleLogoUpload = (info) => {
  if (info.fileList.length > 0) {
    start_upload.value = true;
    start_upload_name.value = info.fileList[0].name;
  }
  if (info.fileList[0].response && info.fileList[0].response.code == 1000) {
    // 上传成功!   开始存数据

    start_upload_loading.value = true;
    start_upload_data.value.name = info.fileList[0].name;
    start_upload_data.value.url = info.fileList[0].response.data.fileUrl;
  }
};

// 打开预览 音频 弹窗  做音频的裁剪
const audioDialog = ref(null);
const start_upload_data = ref({});

const toAudio = (data) => {
  start_upload_data.value.name = data.name;
  start_upload_data.value.url = data.url;
  start_upload_data.value.id = data.id;
  start_upload_data.value.material_duration = data.material_duration;
  audioDialog.value && audioDialog.value.showModal(data);
};

// 上传音频 -- 素材库上传
const addVisible = ref(false);
// 是否是替换
const replay = ref(false);

const audio_name = ref("");
const cancel = (data) => {
  console.log(data, "选择的素材");
  if (!!data) {
    // 如果是替换素材
    if (replay.value) {
      // 替换渲染数组中的此项
      const index = start_upload_Alldata.value.findIndex(
        (ele) => ele.id == start_upload_data.value.id
      );
      if (index != -1) {
        start_upload_Alldata.value[index] = {
          id: data.id,
          url: data.material_url, // 音频路径
          name: data.material_name, // 音频名字
          isOK: true, // 是否转码 成功
          material_duration: data.material_duration,
          media_id: data?.oss_media_id || "",
        };
      } else {
        start_upload_Alldata.value.push({
          id: data.id,
          url: data.material_url, // 音频路径
          name: data.material_name, // 音频名字
          isOK: true, // 是否转码 成功
          material_duration: data.material_duration,
          media_id: data?.oss_media_id || "",
        });
      }
      // 修改传递给弹窗的值
      start_upload_data.value = {
        id: data.id,
        url: data.material_url, // 音频路径
        name: data.material_name, // 音频名字
        material_duration: data.material_duration,
        media_id: data?.oss_media_id || "",
      };
      nextTick(() => {
        audioDialog.value &&
          audioDialog.value.initCanvasFn(start_upload_data.value);
      });
    } else {
      start_upload_Alldata.value.push({
        id: data.id,
        url: data.material_url, // 音频路径
        name: data.material_name, // 音频名字
        isOK: true, // 是否转码 成功
        material_duration: data.material_duration,
        media_id: data?.oss_media_id || "",
      });
      audio_name.value = data.material_name;
    }
    addVisible.value = false;
  } else {
    addVisible.value = false;
  }
};

// 删除镜头组
const del_upload_Alldata = (index) => {
  start_upload_Alldata.value.splice(index, 1);
};

// 带着id 轮训音频拆分的结果
const timerId = ref(null);
const closeedLoading = ref(false);
const showAudio = computed(() => {
  return dataSeparation.value.tts_config_audio.some(
    (ele) => ele.audio_url != ""
  );
});
// 音频字幕的数据  获取及处理
const initData = async (data) => {
  try {
    closeedLoading.value = false;
    const res = await request.get(
      "/work_ai",
      `/user/shotstack/parseAudioToTxt/get`,
      {
        TaskId: data.id,
      }
    );

    if (res.result.Data.StatusStr !== "success") {
      // 继续轮训
      timerId.value = setTimeout(() => {
        initData(data);
        return;
      }, 5000);
    } else {
      closeedLoading.value = true;
      if (res.result.captions.length == 0) {
        message.warning("未识别到音频, 请重试!");
        audioDialog.value.updateSaveLoading(false);
        audioDialog.value.closeLodingDialog();
        return;
      }
      if (dataSeparation.value.tts_config_audio.length < 5) {
        // 关闭loading 状态 这里是父元素 传一个状态值 给子元素
        closeedLoading.value = true;
        const tts_data = baseTts_config();
        tts_data.subtitle = JSON.parse(
          JSON.stringify(dataSeparation.value.tts_config_audio[0].subtitle)
        );
        tts_data.iccts[0].elements = [];
        tts_data.tab_id = "audio";
        console.log(res.result, "音频的结果");

        // 基础的subtitle数据
        const sub = JSON.parse(
          JSON.stringify(dataSeparation.value.tts_config_audio[0].subtitle[0])
        );

        let importSubtitle = [];
        // 基础的字体大小
        const font_size = +sub.font_size / scaleData.value.scaleWidth;

        for (
          let sub_item = 0;
          sub_item < res.result.captions.captionsShow.length;
          sub_item++
        ) {
          const item = res.result.captions.captionsShow[sub_item];
          item.EndMs = item.EndMs * 1000;
          item.StartMs = item.StartMs * 1000;
          const textWidth = await getTextWidthUsingCanvas(
            item?.FinalSentence,
            font_size,
            sub.font_family
          );

          importSubtitle[sub_item] = {
            ...JSON.parse(JSON.stringify(sub)),
            text: item?.FinalSentence || "",
            ssml: "<speak>" + item?.FinalSentence + "</speak>",
            subtitle_id: nanoid(),
            x: sub.showX - textWidth / 2,
            y: sizeData.value.draggableHeight / subtitleHeightratio,
            material_path: "",
            audio_url: "",
            start_time: item.StartMs,
            end_time: item.EndMs,
            duration: item.EndMs - item.StartMs,
          };
        }

        console.log(
          importSubtitle,
          "importSubtitleimportSubtitleimportSubtitleimportSubtitle"
        );
        tts_data.subtitle = importSubtitle;
        tts_data.tab_id = "audio";
        tts_data.audio_url = data.url;
        tts_data.start_time = data.start_time;
        tts_data.end_time = data.end_time;
        tts_data.duration = tts_data.end_time - tts_data.start_time;
        tts_data.ssmlContent = importSubtitle
          .map(
            (ele) =>
              `<speak subId="${ele.subtitle_id}" tts_id="${tts_data.tts_id}">${ele.text}</speak>`
          )
          .join("");
        tts_data.media_id = data?.media_id || "";

        // 新增 音频使用次数 需求  --新增id
        const matchingMaterial = start_upload_Alldata.value.find(
          (item) => item.url === data.url
        );
        if (matchingMaterial) {
          tts_data.audio_material_id = matchingMaterial.id;
        }

        // 只有确保音频项只有一个 且内部的字幕为空, 才替换第一项, 否则新增
        dataSeparation.value.tts_config_audio.length == 1 &&
          dataSeparation.value.tts_config_audio[0].subtitle.length == 1 &&
          dataSeparation.value.tts_config_audio[0].subtitle[0].text == ""
          ? (dataSeparation.value.tts_config_audio[0] = Object.assign(
            dataSeparation.value.tts_config_audio[0],
            tts_data
          ))
          : Global_tts_config.value.configs.push(tts_data);
        store.commit("INIT_GLOBALTTSCONFIG_DATA", Global_tts_config.value);
        currentId.value = tts_data.tts_id;

        // 关闭音频分离的相关弹窗
        audioDialog.value.reset();
      } else {
        // 最多加5项
        // 关闭loding层弹窗
        audioDialog.value.closeLodingDialog();
        message.warning("最多添加5个字幕!");
      }
      audioDialog.value.updateSaveLoading(false);
      audioDialog.value.closeLodingDialog();
    }
  } catch (error) {
    audioDialog.value.updateSaveLoading(false);
    audioDialog.value.closeLodingDialog();
  }
};

const update = (data) => {
  initData(data);
};

const ReAdd = (url) => {
  replay.value = true;
  addVisible.value = true;
};

// 所有音频的富文本节点
const Global_TextEditingAudioRef = ref([]);
// 所有手动设置字幕的富文本节点
const Global_TextEditingRef = ref([]);
// 导入数据回调
const updateAiData = (data) => {
  console.log(
    data,
    "导入数据回调导入数据回调导入数据回调导入数据回调导入数据回调"
  );
  // Global_tts_config.value
  store.commit(
    "INIT_GLOBALTTSCONFIG_DATA",
    JSON.parse(
      JSON.stringify({ ...JSON.parse(JSON.stringify(data.global_tts_config)) })
    )
  );

  nextTick(() => {
    // 更新富文本组件数据
    Global_TextEditingRef.value.forEach((ele) => {
      ele.updateRichText();
    });

    nextTick(() => {
      // 展开第0项
      const target = data.global_tts_config.configs[0].tts_id;
      foldManual(target);
    });
  });
};

// 关闭弹窗, 取消轮询
const cancelLoding = () => {
  timerId.value && clearTimeout(timerId.value);
};

// 打开文案库选择
const openCopyLibraryModal = (type = "open") => {
  if (type == "open") {
    copyLibraryModal.value.showModal();
  } else {
    copyLibraryModal.value.closeModal();
  }
};

// 导入文案之后的步骤
const importNextStep = (result) => {
  Global_tts_config.value.configs = [
    ...result,
    ...dataSeparation.value.tts_config_audio,
  ];
  store.commit("INIT_GLOBALTTSCONFIG_DATA", Global_tts_config.value);
  nextTick(() => {
    // 更新富文本组件数据
    Global_TextEditingRef.value.forEach((ele) => {
      ele.updateRichText();
    });

    // 展开第0项
    nextTick(() => {
      const target = result[0].tts_id;
      foldManual(target);
    });
  });
};

// 文案库选择文案回调
const closeChooseMaterial = async (data) => {

  console.log(data, "选择的文案");
  if (!Array.isArray(data) || (Array.isArray(data) && data.length == 0))
    return message.error("请选择文案");
  if (Global_tts_config.value.configs_type != "text") return;
  const result = importListToRichtext({
    data,
    sizeData,
    xLocation,
    dataSeparation,
    scaleData,
    getTextWidthUsingCanvas,
    subtitleHeightratio,
    Global_tts_config,
    key: "material_content",
  });

  // return
  importNextStep(result);
};

// 打开文案仿写弹窗
const openTextImitation = () => {
  TextImitationDialogRef.value.showModal();
};

// 获得文案仿写返回的数据
const getTextArr = (list) => {
  console.log(list, "传递过来的list");
  if (!Array.isArray(list) || (Array.isArray(list) && list.length == 0))
    return message.error("请选择文案");
  if (Global_tts_config.value.configs_type != "text") return;
  const result = importListToRichtext({
    data: list,
    sizeData,
    xLocation,
    dataSeparation,
    scaleData,
    getTextWidthUsingCanvas,
    subtitleHeightratio,
    Global_tts_config,
    key: "content",
  });
  // 数据处理完毕后的步骤
  importNextStep(result);
  TextImitationDialogRef.value.closeModal();
};

defineExpose({
  openDrawer,
  closeDrawer,
  showUploadState,
});
</script>

<template>
  <div class="SubtitledubbingDrawer">
    <transition name="fade">
      <a-drawer v-model:visible="visible" class="custom-class"
        style="color: red; min-width: 420px; z-index: 200 !important" placement="right" :bodyStyle="{
          paddingTop: 0,
        }" :closable="false" :maskClosable="false" :keyboard="false" width="50%" :destroyOnClose="true" v-if="visible">
        <slot name="title">
          <div class="title_box">
            <div class="title_top">
              <h1 class="title">{{ props.title }}</h1>
              <div class="close" @click="closeDrawer">
                <CloseOutlined />
              </div>
            </div>
          </div>
        </slot>
        <div class="content">
          <!-- 添加字幕标题 -->
          <div class="content_item">
            <div class="content_item_title">
              <h2>添加字幕内容</h2>
              <span>如果添加了多组字幕&配音，将被平均分配给镜头组合</span>
            </div>

            <div class="switch" style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              ">
              <div class="switch_box">
                <!--   点击 切换按钮 控制下面页面的显示与影藏 -->
                <div class="switch_item" :class="{
                  activeSwitch: Global_tts_config.configs_type == 'text',
                }" @click="switchDisplay('text')">
                  手动设置字幕
                </div>
                <div class="switch_item" :class="{
                  activeSwitch: Global_tts_config.configs_type == 'audio',
                }" @click="switchDisplay('audio')">
                  音频生成字幕
                </div>
              </div>

              <div class="content_item_AI">
                <template v-if="Global_tts_config.configs_type == 'text'">
                  <a-button size="small" @click="openCopyLibraryModal('open')"
                    style="display: flex; align-items: center">
                    <cu-icon class="icon" type="icon-bendiwenanku"></cu-icon>
                    文案库选择
                  </a-button>
                  <a-button size="small" :loading="iconLoading" @click="openTextImitation"
                    style="display: flex; align-items: center">
                    <cu-icon class="icon" type="icon-kaishichuangzuo"></cu-icon>
                    文案仿写
                  </a-button>
                </template>
                <a-button size="small" :loading="iconLoading" @click="openAI"
                  style="display: flex; align-items: center">
                  <template #icon>
                    <cu-icon type="icon-AIxiezuozhushou"
                      style="color: #2580fd; font-size: 18px; margin-top: 3px"></cu-icon>
                  </template>
                  AI写作助手
                </a-button>
              </div>
            </div>

            <!-- 全局字幕富文本-音频 -->
            <div class="switch_display_box" v-show="Global_tts_config.configs_type == 'audio'">
              <!-- 素材库导入 -->
              <div class="upload_btn_box">
                <a-button type="primary" style="border-radius: 7px" @click="addVisible = true">
                  <UploadOutlined /> 素材库导入
                </a-button>
                <!-- 头部生成字幕选项 -->
                <div style="display: flex; align-items: center; width: 100%" v-for="item in start_upload_Alldata"
                  :key="item.id">
                  <div class="upload_one">
                    <div class="upload_one_left">
                      <FileDoneOutlined style="font-size: 16px; color: rgb(66, 70, 78)" />
                      <div class="upload_one_left_tile">
                        {{ item.name }}
                      </div>
                    </div>
                    <div class="upload_one_right">
                      <span v-if="item.isOK == false" style="color: #0c0d0e">
                        上传中
                        <loadingOutlined />
                      </span>
                      <a-button v-else size="small" style="border-radius: 7px; padding: 0 12px" @click="toAudio(item)">
                        生成字幕
                      </a-button>
                    </div>
                  </div>
                  <a-popconfirm placement="topLeft" title="确认删除?" ok-text="确定" cancel-text="取消" trigger="click"
                    @confirm="del_upload_Alldata(index)">
                    <DeleteOutlined v-if="item.isOK == true" style="
                        font-size: 16px;
                        color: rgb(66, 70, 78);
                        margin: 18px 0 0 5px;
                        cursor: pointer;
                      " />
                  </a-popconfirm>
                </div>
              </div>

              <!-- 富文本主体 -->
              <div v-show="Global_tts_config.configs_type == 'audio' && showAudio">
                <template v-for="(i, index) in dataSeparation.tts_config_audio" :key="i.tts_id">
                  <div v-show="currentId == i.tts_id">
                    <Global_TextEditing :ref="(el) => (Global_TextEditingAudioRef[index] = el)" :tts_id="i.tts_id"
                      :showIndex="index" :tab_id="i.tab_id">
                    </Global_TextEditing>
                  </div>
                  <!-- 折叠起来的样式 -->
                  <div v-show="currentId != i.tts_id" class="fold_manual_box" @click="foldManual(i.tts_id)">
                    <div class="fold_manual_title">
                      {{ "字幕" + (index + 1) }}
                    </div>
                    <div class="edit_show_msg" v-if="!!Global_TextEditingAudioRef?.[index]">
                      <!-- 文本预计时长 -->
                      <div class="duration">
                        预计时长:
                        <span class="time_content">{{
                          Global_TextEditingAudioRef[index].duration
                        }}</span>秒
                      </div>

                      <!-- 文本字数进度 -->
                      <div :class="{
                        'character-count': true,
                        'character-count--warning':
                          Global_TextEditingAudioRef?.[index]?.text_num ===
                          Global_TextEditingAudioRef?.[index]?.limit,
                      }">
                        <svg height="20" width="20" viewBox="0 0 20 20">
                          <circle r="10" cx="10" cy="10" fill="#e9ecef" />
                          <circle r="5" cx="10" cy="10" fill="transparent" stroke="currentColor" stroke-width="10"
                            :stroke-dasharray="`calc(${Math.round(
                              (100 /
                                Global_TextEditingAudioRef?.[index]?.limit) *
                              Global_TextEditingAudioRef?.[index]?.text_num
                            )} * 31.4 / 100) 31.4`" transform="rotate(-90) translate(-20)" />
                          <circle r="6" cx="10" cy="10" fill="white" />
                        </svg>
                        {{ Global_TextEditingAudioRef?.[index]?.text_num }} /
                        {{ Global_TextEditingAudioRef?.[index]?.limit }}
                        <br />
                      </div>
                    </div>
                  </div>
                  <!-- <div v-show="currentId != i.tts_id">
                    <div class="fold_manual_box" @click="foldManual(i.tts_id)">
                      {{ "字幕" + (index + 1) }}
                    </div>
                  </div> -->
                </template>
              </div>
            </div>

            <!-- 全局字幕富文本-手动设置 -->
            <div class="switch_display_box" v-show="Global_tts_config.configs_type == 'text'">
              <template v-for="(i, index) in dataSeparation.tts_config_text" :key="i.tts_id">
                <div v-show="currentId == i.tts_id">
                  <Global_TextEditing :ref="(el) => (Global_TextEditingRef[index] = el)" :showIndex="index"
                    :tts_id="i.tts_id" :tab_id="i.tab_id"></Global_TextEditing>
                </div>

                <!-- 折叠起来的样式 -->
                <div v-show="currentId != i.tts_id" class="fold_manual_box" @click="foldManual(i.tts_id)">
                  <div class="fold_manual_title">
                    {{ "字幕" + (index + 1) }}
                  </div>
                  <div class="edit_show_msg" v-if="!!Global_TextEditingRef?.[index]">
                    <!-- 文本预计时长 -->
                    <div class="duration">
                      预计时长:
                      <span class="time_content">{{
                        Global_TextEditingRef[index].duration
                      }}</span>秒
                    </div>

                    <!-- 文本字数进度 -->
                    <div :class="{
                      'character-count': true,
                      'character-count--warning':
                        Global_TextEditingRef?.[index]?.text_num ===
                        Global_TextEditingRef?.[index]?.limit,
                    }">
                      <svg height="20" width="20" viewBox="0 0 20 20">
                        <circle r="10" cx="10" cy="10" fill="#e9ecef" />
                        <circle r="5" cx="10" cy="10" fill="transparent" stroke="currentColor" stroke-width="10"
                          :stroke-dasharray="`calc(${Math.round(
                            (100 / Global_TextEditingRef?.[index]?.limit) *
                            Global_TextEditingRef?.[index]?.text_num
                          )} * 31.4 / 100) 31.4`" transform="rotate(-90) translate(-20)" />
                        <circle r="6" cx="10" cy="10" fill="white" />
                      </svg>
                      {{ Global_TextEditingRef?.[index]?.text_num }} /
                      {{ Global_TextEditingRef?.[index]?.limit }}
                      <br />
                    </div>
                  </div>
                </div>
                <!-- <div v-show="currentId != i.tts_id">
                  <div class="fold_manual_box" @click="foldManual(i.tts_id)">
                    {{ "字幕" + (index + 1) }}
                  </div>
                </div> -->
              </template>
              <!-- 添加字幕 -->
              <a-button class="add_subtitle_btn" type="dashed" @click="addeditorArr" ghost>
                <PlusOutlined />添加字幕
              </a-button>
            </div>

            <!-- 添加字幕标题 -->
            <div class="content_item" style="margin-top: 40px">
              <div class="content_item_title"></div>
              <!-- 花字 and 配音组件 -->
              <SubtitlesFontStyleComponent :configs_type="Global_tts_config?.configs_type"
                ref="Subtitles_FontStyleComponent" />
            </div>
          </div>

          <div id="phoneConCover" class="phoneConCover_content" :style="{
            opacity: phoneVisible ? 1 : 0,
            transition: 'opacity 0.5s',
          }">
            <!-- 手机头部 -->
            <div class="mobile-header">
              <div class="time">{{ dayjs().format("HH:mm") }}</div>
              <div class="wife">
                <cu-icon type="icon-xinhao" style="font-size: 12px"></cu-icon>
                <cu-icon type="icon-wife" style="margin: 0 2px; font-size: 14px"></cu-icon>
                <cu-icon type="icon-electricity-full" style="font-size: 14px"></cu-icon>
              </div>
            </div>
            <!-- 模拟抖音背景 -->
            <div class="bgc_content" :style="{
              'background-image': showImg
                ? `url(${utils.staticPath + 'images/workAi/shotstack/bg_cover.png'
                })`
                : '',
            }"></div>
            <!-- 素材背景图 -->
            <div class="bgc_content" :style="{
              ...parentBgc,
              'z-index': 1,
              height: '640px',
              top: '45px',
              left: 0
            }"></div>
            <!-- 底层背景图 -->
            <div class="left_phone_view" :style="{
              ...bgc
            }">
              <!-- <div class="left_phone_view"> -->
              <!-- <a-spin style="width: 100%; height: 640px" :spinning="loading"> -->
              <DraggableContainer :style="resizableStyle" :referenceLineColor="'white'">
                <!-- @resize-end="resizeEndHandle"   -->
                <Vue3DraggableResizable style="transform: translateX(-50%)" v-model:x="editSubtitleItem.x"
                  v-model:y="editSubtitleItem.y" v-model:w="ResizableWidth" v-model:h="Resizableheight"
                  v-model:active="ResizableActive" :resizable="false" :draggable="true" :parent="false"
                  @drag-end="dragEndHandle">
                  <!-- @drag-end="dragEndHandle" -->
                  <!-- :textContent.prop="lineMsg.data" -->
                  <!-- :initW="ResizableWidth" :initH="Resizableheight" -->
                  <p :style="{ ...coverStyle(), width: 'calc(100% + 1px)' }" class="editor_content"
                    :textContent.prop="editSubtitleItem.text"></p>
                </Vue3DraggableResizable>
                <div id="editor_content_div" :style="{
                  width: ResizableWidth + 'px',
                  opacity: 0,
                }">
                  <p id="editor_content_p" :style="{ ...coverStyle() }" class="editor_content"
                    :textContent.prop="editSubtitleItem.text"></p>
                </div>
              </DraggableContainer>
              <!-- </a-spin> -->
            </div>
            <div class="bottom_View_control">
              <a-button @click="showImg = !showImg">{{ showImg ? "关闭" : "开启" }}抖音视图</a-button>
            </div>
          </div>
        </div>

        <template #footer>
          <div class="bottom_btn">
            <a-button style="margin-right: 15px" @click="close">取消</a-button>
            <a-button type="primary" @click="submitConfirm" :loading="submitLoading">确定</a-button>
          </div>
        </template>

        <AIWritingAssistant ref="aiWritingAssistant" :isQuanJU="true" @updateAiData="updateAiData" />
      </a-drawer>
    </transition>

    <!-- 查看音频 -->
    <ViewAudioModel ref="audioDialog" :start_upload_data="start_upload_data" :closeedLoading="closeedLoading"
      @update="update" @ReAdd="ReAdd" @audioLoading="audioLoading" @cancelLoding="cancelLoding">
      <!-- :start_upload_data="start_upload_data" :closeedLoading="closeedLoading"
      @update="update" @cancelLoding="cancelLoding" @audioLoading="audioLoading" @ReAdd="emit('openUpLoad', 'replay')" -->
    </ViewAudioModel>
    <!-- 预览自定义音色的音频节点 -->
    <audio @ended="handleGlobalAudioEnded" ref="globalAudio" :src="playingItem" style="display: none"></audio>
    <!-- 选择音频上传 -->
    <ChooseMaterial :isClip="false" material_type="audio" :visible="addVisible" @close="cancel" />

    <!-- 文案库 -->
    <CopyLibraryModal ref="copyLibraryModal" selectType="checkbox" @importSuccess="closeChooseMaterial" />

    <!-- 文案仿写组件 -->
    <TextImitationDialog ref="TextImitationDialogRef" :isComponents="true" @getTextArr="getTextArr">
    </TextImitationDialog>
    <!-- <newChooseMaterial :isClip="true" :visible="addVisible" modelType="audio" @close="cancel" /> -->
  </div>
</template>

<style scoped lang="less">
// 折叠起来的样式
// 每一项富文本折起来的样式
.fold_manual_box {
  width: 100%;
  line-height: 33px;
  background-color: #f6f8fa;
  padding: 1px 15px;
  cursor: pointer;
  border-radius: 5px;
  margin-top: 10px;
  font-size: 12px;
  color: #737a87;
  display: flex;
  align-items: center;
  // justify-content: space-between;
  gap: 0 15px;
  border: 1px solid transparent;
  transition: all 0.3s;

  &:hover {
    border-color: var(--ss-primary-color-hover);
  }

  // 折叠起来的样式
  .fold_manual_title {}

  .edit_show_msg {
    display: flex;
    align-items: center;
    gap: 10px;

    .duration {
      color: #737a87;
    }

    // 文本上限提示
    .character-count {
      align-items: center;
      color: var(--ss-primary-5);
      display: flex;
      font-size: 0.75rem;
      gap: 0.5rem;

      svg {
        color: var(--ss-primary-5);
      }

      &--warning,
      &--warning svg {
        color: red;
      }
    }
  }
}

// .fold_manual_box {
//   width: 100%;
//   line-height: 33px;
//   background-color: #f6f8fa;
//   padding: 1px 15px;
//   cursor: pointer;
//   border-radius: 5px;
//   margin-top: 10px;
//   font-size: 12px;
//   color: #737a87;
// }

// 头部样式
.title_box {
  width: 100%;
  padding-bottom: 10px;
  padding-top: 24px;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 999;

  &::after {
    content: "";
    height: 1px;
    width: calc(100% + 48px);
    background-color: #e8e8e8;
    position: absolute;
    bottom: 0;
    left: -24px;
  }

  .title_top {
    display: flex;
    justify-content: space-between;
    color: #0c0d0e;

    // margin-bottom: 10px;
    h1 {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .close {
      cursor: pointer;
      text-align: center;
      line-height: 29px;
      padding: 0 6px;

      &:hover {
        background-color: #f3f3f4;
      }
    }
  }

  .title_bottom {
    .btn_prev {
      border-radius: 5px;
      padding: 0 16px;
      font-size: 12px;
      height: 28px;
    }
  }
}

// 整体样式
.content {
  padding-top: 20px;
  position: relative;

  // 手机样式
  .phoneConCover_content {
    width: 360px;
    height: 730px;
    position: fixed;
    border-radius: 20px;
    top: 50%;
    left: calc(calc(100% - 50%) / 2);
    transform: translate(-50%, -50%);
    background-color: #000;
    display: flex;
    align-items: center;
    justify-content: center;

    .mobile-header {
      height: 44px;
      width: 100%;
      position: absolute;
      left: 0;
      top: 0;
      border-top-left-radius: 20px;
      border-top-right-radius: 20px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);
      background: black;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #fff;
      padding: 10px 10px;
      overflow: hidden;
    }

    // 背景图
    .bgc_content {
      position: absolute;
      top: 50px;
      left: 0;
      width: 100%;
      height: 100%;
      background-repeat: no-repeat;
      background-size: cover;
      background-size: 100%;

      /* 添加这一行 */
      pointer-events: none;
      z-index: 1;
    }

    .left_phone_view {
      overflow: hidden;
      position: relative;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid rgba(255, 255, 255, 0.281);

      .editor_content {
        margin-bottom: 0;
        border: none;
        resize: none;
        height: auto;
        display: inline-block;
        // overflow: hidden;
        // 禁止选中
        pointer-events: none;
        // 换行显示
        white-space: pre-wrap;
        // 不考虑连贯性, 强制换行
        word-break: break-all;
        // transform: translateX(-50%);
        // transform: translateY(-50%);
      }
    }

    // 手机下方的控制按钮
    .bottom_View_control {
      position: absolute;
      bottom: -50px;
      left: 50%;
      transform: translate(-50%, 0);
      display: flex;
    }
  }

  .content_item {
    .upload_btn_box {
      margin-top: 20px;
    }

    .content_item_title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      h2 {
        font-size: 13px;
        font-weight: 600;
        color: #1e1c23;
        margin-bottom: 0;
      }

      span {
        font-size: 12px;
        color: #737a87;
      }
    }

    // 选择字幕内容生成方式
    .switch {
      margin-top: 10px;

      .switch_box {
        width: 213px;
        padding: 3px;
        background-color: #f1f3f5;
        display: flex;
        border-radius: 3px;
        overflow: hidden;
        // margin-top: 6px;

        .switch_item {
          line-height: 28px;
          flex: 1;
          font-size: 13px;
          color: #42464e;
          border-radius: 3px;
          overflow: hidden;
          text-align: center;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;

          &:hover {
            color: #3261fb;
          }
        }

        // .switch_AI {
        //   :deep(.ant-btn) {
        //     span {
        //       height: 100%;
        //       line-height: normal;
        //     }
        //   }
        // }
        .activeSwitch {
          background-color: #fff;
          color: #3261fb;
        }
      }

      .content_item_AI {
        display: flex;
        gap: 10px;

        .icon {
          display: flex;
          align-items: center;
          color: #2580fd;
          font-size: 18px;
        }
      }
    }

    // 手动设置字幕 样式
    .manual_box {
      background-color: #f6f8fa;
      padding: 15px;
      margin-top: 18px;
      border-radius: 5px;

      // 编辑容器样式
      .editor_container {
        // min-height: 150px;
        background-color: #fff;
        border-radius: 8px;
        position: relative;
        padding: 7px 20px;
        padding-bottom: 35px;

        .editor_content_box {
          // padding: 8px 52px 30px 28px;
          display: flex;
          flex-direction: column;

          .editor_content_item {
            display: flex;
            flex-direction: column;
            position: relative;

            .editor_content_iatem_box {
              position: relative;

              .editor_content_item_point {
                cursor: pointer;
                color: #c7ccd6;
                position: absolute;
                left: -14px;
                top: 0;
              }

              .editor_content {
                margin-bottom: 0;
                border: none;
                resize: none;
                height: auto;
                display: inline-block;
                overflow: hidden;
                // 禁止选中
                pointer-events: none;
                // 换行显示
                white-space: pre-wrap;
                // 不考虑连贯性, 强制换行
                word-break: break-all;
                // display: inline-block;
              }
            }
          }
        }

        // 每一项 底部的操作按钮容器
        .editor_operation {
          display: flex;
          position: absolute;
          bottom: 5px;
          left: 5px;
          overflow: hidden;

          // 每一项 正常的状态
          .editor_operation_item {
            min-width: 78px;
            display: flex;
            align-items: center;
            gap: 2px;
            margin-right: 6px;
            padding: 2px 8px;
            background-color: #f4f5f5;
            border-radius: 3px;
            overflow: hidden;
            cursor: pointer;
            font-size: 12px;
            color: #1c1f23b3;
            // 静止选取文字
            -webkit-user-select: none;
            /* Safari */
            -moz-user-select: none;
            /* Firefox */
            -ms-user-select: none;
            /* Internet Explorer/Edge */
            user-select: none;

            /* 非前缀版本，适用于Chrome和Opera */
            &:hover {
              background-color: #eceded;
            }
          }

          // 禁用的状态
          .disable_editor_operation_item {
            cursor: not-allowed;
            background-color: #f9fafa;
            color: #aeafb0;

            &:hover {
              background-color: #f9fafa;
              color: #aeafb0;
            }
          }
        }
      }

      // 标题样式
      .manual_title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .title_text {
          font-size: 14px;
          color: #0c0d0e;
          font-weight: 600;
        }

        .operation {
          display: flex;
          align-items: center;
          gap: 10px;

          .delete_btn {
            background-color: #fff;
            border: 1px solid #dde2e9;
            font-size: 13px;
            color: #42464e;
            border-radius: 3px;
            padding: 0px 7px;
            cursor: pointer;

            &:hover {
              border-color: #3261fb;
            }
          }

          .disable_delete_btn {
            cursor: not-allowed;
            border-color: #dde2e9;
            color: #c7ccd6;

            &:hover {
              cursor: not-allowed;
              border-color: #dde2e9;
              color: #c7ccd6;
            }
          }
        }
      }
    }

    // 添加按钮
    .add_subtitle_btn {
      width: 100%;
      color: #42464e;
      margin-top: 10px;
    }
  }
}

// 底部按钮
.bottom_btn {
  padding: 8px 24px;
  display: flex;
  justify-content: flex-end;
  background-color: #fff;
}

:deep(.ant-upload-list-item-info) {
  display: none !important;
}

:deep(.ant-progress-outer) {
  display: none !important;
}

:deep(.ant-upload-list) {
  display: none !important;
}

:deep(.ant-upload-list-text) {
  display: none !important;
}

.upload_one {
  width: 97%;
  background-color: #f5f7f9;
  margin-top: 20px;
  padding: 6px 12px;
  display: flex;
  justify-content: space-between;

  .upload_one_left {
    width: 85%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .upload_one_left_tile {
    width: 96%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #0c0d0e;
  }
}

.ant-popover-buttons {
  display: flex !important;
}

.manual_audio {
  width: 100%;
  height: 86px;
  background-color: #fff;
  margin-bottom: 20px;
  padding: 14px;
  display: flex;

  .video_box_left_one {
    width: 50px;
    height: 50px;
    background-color: #bec0c2;
    border-radius: 3px;
    text-align: center;
    line-height: 56px;
    margin-right: 20px;
  }

  .manual_audio_right {
    color: #000;
    flex: 1;

    .manual_audio_right_top {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      font-size: 14px;
      font-weight: 600;
      color: #000;
      margin-bottom: 5px;
    }
  }
}
</style>
